package com.dayuanit.atm.service;

import com.dayuanit.atm.entity.User;
import com.dayuanit.atm.exception.BizException;
import com.dayuanit.atm.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserService {

    private static Logger logger = LoggerFactory.getLogger(UserService.class);
    @Autowired
    private UserMapper userMapper;

    public User login(String username, String pwd) {

        logger.info("username={}, pwd={},sex={}，price={}", username, pwd);

        if (StringUtils.isBlank(username) || StringUtils.isBlank(pwd)) {
            throw new BizException("请输入用户名和密码");
        }

        final User user = userMapper.getUser(username);
        if (null == user) {
            throw new BizException("用户不存在或者密码错误");
        }

        if (!user.getPassword().equals(pwd)) {
            throw new BizException("用户不存在或者密码错误");
        }

        return user;
    }

    public void regist(String username, String pwd, String confirmPwd) {
        if (StringUtils.isBlank(username) ||
                StringUtils.isBlank(pwd) ||
                StringUtils.isBlank(confirmPwd)) {
            throw new BizException("请输入用户名和密码");
        }

        if (!pwd.equals(confirmPwd)) {
            throw new BizException("两次密码不一致");
        }

        User user = userMapper.getUser(username);
        if (null != user) {
            throw new BizException("用户名已存在");
        }

        user = new User();
        user.setUsername(username);
        user.setPassword(pwd);
        user.setCreateTime(new Date());
        int rows = userMapper.insert(user);
        if (1 != rows) {
            throw new BizException("注册失败");
        }
    }
}
